import type { AppContext } from '@/common/hooks'
// #ifdef SUBSCRIPTION || PRIVATE
import { wxPay as mpWxPay } from '@/common/wxinit'
// #endif
import type { MpPaymentParams } from '@/common/wxinit'
import type { WxPaymentParams } from '@/typings/utils'
import  { sys } from '@/common/utils'
import {PayType} from '@/env'


export const stripePay = (url : string) => {
	// #ifdef APP-PLUS
	plus.runtime.openURL(url, err => {
		console.log(err)
	})
	// #endif
	//  #ifdef H5
	// 加top，处理iframe跳转问题,window无法跳出iframe
	top!.location.href = url
	// #endif
}

export const yaBandPay = (data : any) => {
	// #ifdef APP-PLUS
	plus.runtime.openURL(data.url, err => {
		console.log(err)
	})

	// #endif
	//  #ifdef H5
	top!.location.href = data
	// #endif
}

// #ifdef MP-WEIXIN





export const wxPay = (params : MpPaymentParams, successCallBack ?: WxPaymentParams['success'], failCallBack ?: WxPaymentParams['fail'], cancelBack : WxPaymentParams['complete'] = () => { }) => {
	wx.requestPayment({
		timeStamp: params.timeStamp,
		nonceStr: params.nonceStr,
		package: params.package,
		signType: params.signType,
		paySign: params.paySign,
		success: successCallBack,
		fail: failCallBack,
		complete: cancelBack
	})
}

type OrderPaymentParams = Parameters<typeof wx.requestOrderPayment>[0]

export const wxOrderPay = (params : MpPaymentParams, successCallBack ?: OrderPaymentParams['success'], failCallBack ?: OrderPaymentParams['fail'], cancelBack : OrderPaymentParams['complete'] = () => { }) => {
	let data : OrderPaymentParams = {
		timeStamp: params.timeStamp,
		nonceStr: params.nonceStr,
		package: params.package,
		signType: params.signType,
		paySign: params.paySign,
		success: successCallBack,
		fail: failCallBack,
		complete: cancelBack
	}
	if (params.orderInfo) {
		data['orderInfo'] = params.orderInfo
	}
	wx.requestOrderPayment(data)
}

// #endif

export const mpAppPay = ({
	payParams,
	isTrace,
	requireOrder
} : {
	payParams : MpPaymentParams
	isTrace ?: boolean
	requireOrder ?: boolean
}) =>
	new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN || SUBSCRIPTION || PRIVATE
		let wxPayApi:typeof wxPay|typeof mpWxPay
		// #ifdef SUBSCRIPTION || PRIVATE
		wxPayApi = mpWxPay
		// #endif
		// #ifdef MP-WEIXIN
		wxPayApi = wxPay
		// #endif
		// #ifdef MP-WEIXIN
		if (isTrace) {
			wxPayApi = wxOrderPay
		}
		if (!requireOrder && payParams.orderInfo) {
			delete payParams.orderInfo
		}
		// #endif
		
		console.log(payParams)
		wxPayApi(
			payParams,
			() => {
				resolve({})
			},
			(err) => {
				console.log('小程序或公众号支付失败', err)
				uni.hideLoading()
				reject()
			}
		)
		// #endif
	})


export const sandPay = function (this : AppContext, {
	payParams
} : {
	payParams : any
}) {
	return new Promise((resolve, reject) => {
		//  #ifdef H5
		resolve({
			code: 200,
		})
		// #endif

		// #ifdef APP-PLUS
		let dcSDPLib : any
		if (sys().platform == 'ios') {
			dcSDPLib = uni.requireNativePlugin("HMPTLib-HMPLibModule")
		} else {
			dcSDPLib = uni.requireNativePlugin('SandPayTypeModule')
		}
		let sandPayMethod
		if (sys().platform == 'ios') {
			sandPayMethod = dcSDPLib.sandHMPCashierPayMethod
		} else {
			sandPayMethod = dcSDPLib.cashierPay
		}
		sandPayMethod(
			payParams,
			(ret : any) => {
				uni.hideLoading()
				if (typeof ret === 'string') {
					ret = JSON.parse(ret)
				}
				// 区分微信和支付宝 微信02010005 支付宝02020004 支付宝付码02020006
				// 只有微信才由uniapp拉起小程序完成支付，其他都由插件拉起支付
				if (ret.funcCode === '01010005') {
					plus.share.getServices(shareList => {
						let sweixin = shareList.find(val => val.id == 'weixin')
						if (sweixin) {
							sweixin.launchMiniProgram({
								id: 'gh_fc2c837222f4', //小程序原始id
								path: 'pages/zf/index?token_id=' + ret.tokenId + '&funcCode=01010005',
								type: 0 //正式版:0; 开发版:1; 体验版:2
							})
							this.$showModal({
								content: this.$t('classify.是否支付成功'),
								success: res => {
									if (res.confirm) {
										resolve({})
									} else {
										reject()
									}
								}
							})
						} else {
							this.$toastApp("未安装微信,无法打开对应小程序")
							reject()
						}
					}, e => {
						this.$toastApp("获取微信服务列表失败:" + JSON.stringify(e))

						reject()
					})
				} else {
					if (ret.resultCode === '0000') {
						resolve({})
					} else {
						reject()
					}
				}
			}
		)

		// #endif
	})
}

export const alimappPay = ({
		payParams
	}:{payParams:{payData:string}}) =>
	new Promise((resolve, reject) => {
		// #ifdef MP-ALIPAY
		const payData = JSON.parse(payParams.payData)
		my.tradePay({
			// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号 trade_no
			tradeNO: payData.alipayTradeNo,
			success: () => {
				resolve({})
			},
			fail: (err:any) => {
				console.log('支付宝小程序支付失败', err)
				uni.hideLoading()
				reject()
			}
		});
		// #endif
	})
	
export const appPay = ({
		payType,
		payParams
	}:{
		payType:PayType.ZFB|PayType.WX
		payParams: string
	}) =>
	new Promise((resolve, reject) => {
		// #ifdef APP-PLUS
		// app下判断是微信支付还是支付宝支付
		let orderInfo
		let provider:Parameters<typeof uni.requestPayment>[0]['provider']

		if (process.env.NODE_ENV === 'development') {
			console.log(payParams, 'payinfo')
		}

		if (payType === PayType.ZFB) {
			provider = 'alipay'
			orderInfo = payParams
		} else {
			let appPayInfo = JSON.parse(payParams)
			provider = 'wxpay'
			orderInfo = {
				appid: appPayInfo.appId,
				noncestr: appPayInfo.nonceStr,
				package: appPayInfo.package,
				partnerid: appPayInfo.partnerId,
				prepayid: appPayInfo.prepayId,
				timestamp: Number(appPayInfo.timeStamp),
				sign: appPayInfo.sign
			}
		}
		if (process.env.NODE_ENV === 'development') {
			console.log(orderInfo, 'orderInfo')
		}

		uni.requestPayment({
			provider,
			orderInfo,
			success: () => {
				resolve({})
			},
			fail: e => {
				console.log('appPayfail', e)
				reject()
			}
		})

		// #endif
	})